<template>
  <view 
    class="floating-ball"
    :style="{ 
      transform: `translate3d(${ballPosition.x}px, ${ballPosition.y}px, 0)`,
      transition: isDragging ? 'none' : 'transform 0.3s ease'
    }"
    @touchstart="onTouchStart"
    @touchmove="onTouchMove"
    @touchend="onTouchEnd"
  >
    <image 
      :src="imageUrl" 
      class="ball-image" 
      mode="aspectFit"
    ></image>
  </view>
</template>

<script>
import { ref, onMounted } from 'vue';
export default {
  name: 'HoverBall',
  props: {
    // 图片URL
    imageUrl: {
      type: String,
      default: ''
    },
    // 跳转路径
    targetPath: {
      type: String,
      default: ''
    },
    // 跳转类型：'navigateTo' | 'switchTab' | 'redirectTo'
    navigateType: {
      type: String,
      default: 'navigateTo'
    },
    // 初始位置：'bottomRight' | 'bottomLeft' | 'topRight' | 'topLeft'
    initialPosition: {
      type: String,
      default: 'bottomRight'
    },
    // 悬浮球大小
    size: {
      type: Number,
      default: 60
    }
  },
  emits: ['ballClick'],
  setup(props, { emit }) {
    const ballPosition = ref({ x: 0, y: 0 });
    const isDragging = ref(false);
    const startPosition = ref({ x: 0, y: 0 });
    const screenWidth = ref(0);
    const screenHeight = ref(0);
    const clickTimer = ref(null);
    const lastClickTime = ref(0);
    const doubleClickDelay = ref(300);

    // 初始化悬浮球位置
    const initBallPosition = () => {
      try {
        const systemInfo = uni.getSystemInfoSync();
        screenWidth.value = systemInfo.windowWidth;
        screenHeight.value = systemInfo.windowHeight;
        const margin = 20; // 边距
        const bottomMargin = 120; // 底部边距（避免遮挡导航栏）
        
        let targetX = 0;
        let targetY = 0;
        
        switch (props.initialPosition) {
          case 'bottomRight':
            targetX = screenWidth.value - props.size - margin;
            targetY = screenHeight.value - props.size - bottomMargin;
            break;
          case 'bottomLeft':
            targetX = margin;
            targetY = screenHeight.value - props.size - bottomMargin;
            break;
          case 'topRight':
            targetX = screenWidth.value - props.size - margin;
            targetY = margin;
            break;
          case 'topLeft':
            targetX = margin;
            targetY = margin;
            break;
          default:
            targetX = screenWidth.value - props.size - margin;
            targetY = screenHeight.value - props.size - bottomMargin;
        }
        
        // 确保位置在屏幕范围内
        targetX = Math.max(0, Math.min(targetX, screenWidth.value - props.size));
        targetY = Math.max(0, Math.min(targetY, screenHeight.value - props.size));
        
        ballPosition.value = { x: targetX, y: targetY };
      } catch (error) {
        // 使用默认位置
        ballPosition.value = { x: 300, y: 500 };
      }
    }

    // 触摸开始
    const onTouchStart = (e) => {
      e.preventDefault();
      e.stopPropagation();
      isDragging.value = false;
      const touch = e.touches[0];
      startPosition.value = {
        x: touch.clientX - ballPosition.value.x,
        y: touch.clientY - ballPosition.value.y
      };
    }

    // 触摸移动
    const onTouchMove = (e) => {
      e.preventDefault();
      e.stopPropagation();
      
      const touch = e.touches[0];
      const deltaX = touch.clientX - startPosition.value.x;
      const deltaY = touch.clientY - startPosition.value.y;
      
      if (!isDragging.value && (Math.abs(deltaX) > 3 || Math.abs(deltaY) > 3)) {
        isDragging.value = true;
      }
      
      if (isDragging.value) {
        let newX = Math.max(0, Math.min(deltaX, screenWidth.value - props.size));
        let newY = Math.max(0, Math.min(deltaY, screenHeight.value - props.size));
        ballPosition.value = { x: newX, y: newY };
      }
    }

    // 触摸结束
    const onTouchEnd = (e) => {
      e.preventDefault();
      e.stopPropagation();
      
      if (isDragging.value) {
        isDragging.value = false;
        return;
      }
      // 未发生拖拽，当成点击
      handleClick();
    }

    // 点击（含双击检测）
    const handleClick = () => {
      const now = Date.now();
      if (clickTimer.value) {
        clearTimeout(clickTimer.value);
        clickTimer.value = null;
      }
      
      // 双击：两次点击时间差小于阈值
      if (now - lastClickTime.value < doubleClickDelay.value) {
        lastClickTime.value = 0;
        
        // 触发双击事件
        emit('ballClick', {
          targetPath: props.targetPath,
          navigateType: props.navigateType,
          clickType: 'double'
        });
        
        // 执行页面跳转
        if (props.targetPath) {
          navigateToTarget();
        }
      } else {
        // 单击：开启定时器，若在阈值内未发生第二次点击，则当作单击
        lastClickTime.value = now;
        clickTimer.value = setTimeout(() => {
          // 触发单击事件
          emit('ballClick', {
            targetPath: props.targetPath,
            navigateType: props.navigateType,
            clickType: 'single'
          });
          
          clickTimer.value = null;
          lastClickTime.value = 0;
        }, doubleClickDelay.value);
      }
    }
    
    // 执行页面跳转
    const navigateToTarget = () => {
      switch (props.navigateType) {
        case 'navigateTo':
          uni.navigateTo({
            url: props.targetPath
          });
          break;
        case 'switchTab':
          uni.switchTab({
            url: props.targetPath
          });
          break;
        case 'redirectTo':
          uni.redirectTo({
            url: props.targetPath
          });
          break;
        default:
          uni.navigateTo({
            url: props.targetPath
          });
      }
    }

    onMounted(() => {
      initBallPosition();
    });

    return {
      ballPosition,
      isDragging,
      startPosition,
      screenWidth,
      screenHeight,
      clickTimer,
      lastClickTime,
      doubleClickDelay,
      initBallPosition,
      onTouchStart,
      onTouchMove,
      onTouchEnd,
      handleClick,
      navigateToTarget
    }
  }
}
</script>

<style lang="scss" scoped>
/* 悬浮球样式 */
.floating-ball {
  position: fixed;
  top: 0;
  left: 0;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: #ffffff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  cursor: pointer;
  user-select: none;
  -webkit-user-select: none;
  -webkit-touch-callout: none;
  -webkit-tap-highlight-color: transparent;
  will-change: transform;
  backface-visibility: hidden;
  transform-style: preserve-3d;
  
  /* 防止页面滚动 */
  touch-action: none;
  -webkit-touch-action: none;
  -webkit-overflow-scrolling: touch;
  
  /* 防止文本选择 */
  -moz-user-select: none;
  -ms-user-select: none;
  
  /* 防止长按菜单 */
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  
  /* 优化渲染性能 */
  contain: layout style paint;
  
  &:active {
    transform: scale(0.95);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  }
  
  /* 拖拽时的样式 */
  &.dragging {
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
    opacity: 0.9;
  }
}

.ball-image {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
  pointer-events: none;
  /* 防止图片拖拽 */
  -webkit-user-drag: none;
  -khtml-user-drag: none;
  -moz-user-drag: none;
  -o-user-drag: none;
  user-drag: none;
}
</style>